package com.lst.servlet;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.entity.request.FocusReqPara;
import com.lst.entity.response.AttentionResPara;
import com.lst.model.Answer;
import com.lst.model.Attention;
import com.lst.model.JiluLog;
import com.lst.service.AnswerService;
import com.lst.service.AttentionService;
import com.lst.service.ClientNumService;
import com.lst.service.JiluLogService;
import com.lst.service.MstDiscussService;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;


/**
 * @ClassName: FocusListServlet
 * @Description: 关注列表接口
 * 
 */
public class FocusListServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private AttentionService attentionService = ctx.getBean(AttentionService.class);
	
	private MstDiscussService mstDiscussService = ctx.getBean(MstDiscussService.class);
	
	private JiluLogService jiluLogService = ctx.getBean(JiluLogService.class);
	
	private AnswerService answerService = ctx.getBean(AnswerService.class);
	
	private ClientNumService clientNumService = ctx.getBean(ClientNumService.class);
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		AttentionResPara resPara = new AttentionResPara();

		try {
			FocusReqPara reqPara = getReqPara(request);
		
		if(isCheckField(reqPara,resPara)){
			Integer userid = Integer.valueOf(reqPara.getUserid());
			Integer page = Integer.valueOf(reqPara.getPage());
			Integer pagesize = Integer.valueOf(reqPara.getPagesize());	
			
			//查询关注列表
			Map<String, Object> reqMap = new HashMap<String, Object>();		
			reqMap.put("createUser", userid);
			PageBounds pageBounds = new PageBounds(page,pagesize);
			List<Attention> attentionList=attentionService.queryByList(reqMap, pageBounds);
			if(attentionList!=null&&attentionList.size()>0){
				for(Attention attention:attentionList){
					//查询动态的相关信息
					if(attention.getType()==1){
						//查询动态的评论数
						Map<String, Object> dymap = new HashMap<String, Object>();
						dymap.put("enabled", true);
						dymap.put("isDeleted", false);
						dymap.put("tarid",attention.getId());
						dymap.put("type", CommCode.SYSTEM_CARESEL_RANGE_DYNAMIC);
						Integer discussNum = mstDiscussService.queryCountByMap(dymap);
						attention.setDiscussNum(discussNum);
						 //喜欢数量
						Map<String, Object> jlmap2 = new HashMap<String, Object>();
						jlmap2.put("sourceId", attention.getId());
						jlmap2.put("jiluType", CommCode.SYSTEM_CARESEL_LOVE_DYNAMIC);
						int loveNum=jiluLogService.countBySourceId(jlmap2);
						attention.setLoveNum(loveNum);
						
						//喜欢标识
						Map<String, Object> jilumap = new HashMap<String, Object>();
						jilumap.put("jiluType", CommCode.SYSTEM_CARESEL_LOVE_DYNAMIC);
						jilumap.put("isDelete", false);
						jilumap.put("sourceId", attention.getId());
						jilumap.put("createUser", userid);
						JiluLog jilu=jiluLogService.queryByMap(jilumap);
						if(jilu!=null){
							attention.setIsLove(jilu.getIsLove());
						}else{
							attention.setIsLove(false);
						}
						
						//标识是否收藏
						Map<String, Object> fmap = new HashMap<String, Object>();
						fmap.put("enabled", true);
						fmap.put("isdeleted", false);
						fmap.put("clientid", userid);
						fmap.put("actid",attention.getId());
						fmap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_DYNAMIC);
						fmap.put("numtype", CommCode.SYSTEM_COUNT_FAVORITE);
						Integer count = clientNumService.queryCountByMap(fmap);
						if(count>0){
							attention.setIsFavorite(true);
						}else{
							attention.setIsFavorite(false);
						}
						
					}
					
					//查询回答评论量和喜欢量
					if(attention.getType()==2){
						//查询动态的评论数
						Map<String, Object> anmap = new HashMap<String, Object>();
						anmap.put("enabled", true);
						anmap.put("isDeleted", false);
						anmap.put("tarid",attention.getId());
						anmap.put("type", CommCode.SYSTEM_CARESEL_RANGE_ANSWER);
						Integer discussNum = mstDiscussService.queryCountByMap(anmap);
						attention.setDiscussNum(discussNum);
						 //喜欢数量
						Map<String, Object> jlmap = new HashMap<String, Object>();
						jlmap.put("sourceId", attention.getId());
						jlmap.put("jiluType", 2);
						int loveNum=jiluLogService.countBySourceId(jlmap);
						attention.setLoveNum(loveNum);
						
						//喜欢标识
						Map<String, Object> jilumap2 = new HashMap<String, Object>();
						jilumap2.put("jiluType", CommCode.SYSTEM_CARESEL_LOVE_ANSWER);
						jilumap2.put("isDelete", false);
						jilumap2.put("sourceId", attention.getId());
						jilumap2.put("createUser", userid);
						JiluLog jilu=jiluLogService.queryByMap(jilumap2);
						if(jilu!=null){
							attention.setIsLove(jilu.getIsLove());
						}else{
							attention.setIsLove(false);
						}
						
						  //标识是否收藏
						Map<String, Object> fmap = new HashMap<String, Object>();
						fmap.put("enabled", true);
						fmap.put("isdeleted", false);
						fmap.put("clientid", userid);
						fmap.put("actid", attention.getId());
						fmap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_ANSWER);
						fmap.put("numtype", CommCode.SYSTEM_COUNT_FAVORITE);
						Integer count = clientNumService.queryCountByMap(fmap);
						if(count>0){
							attention.setIsFavorite(true);
						}else{
							attention.setIsFavorite(false);
						}
						
					}
					if(attention.getType()==3){
						//标识是否回答过问题
						Map<String,Object> map=new HashMap<String,Object>();
						map.put("answerSourceId", attention.getId());
						map.put("answerCreateUser", userid);
						Answer answer=answerService.selectByMap(map);
						if(answer!=null){
							attention.setIsLove(true);
						}else{
							attention.setIsLove(false);
						}
						
						  //标识是否收藏
						Map<String, Object> fmap = new HashMap<String, Object>();
						fmap.put("enabled", true);
						fmap.put("isdeleted", false);
						fmap.put("clientid", userid);
						fmap.put("actid", attention.getId());
						fmap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_QUESTION);
						fmap.put("numtype", CommCode.SYSTEM_COUNT_FAVORITE);
						Integer count = clientNumService.queryCountByMap(fmap);
						if(count>0){
							attention.setIsFavorite(true);
						}else{
							attention.setIsFavorite(false);
						}
						
					}
					
					
					Date date=attention.getCreateDate();
					SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String str=sdf.format(date);
					attention.setCreateDate2(DateUtil.changeTime(str));	
				}
			}
			resPara.setAttentionlist(attentionList);
			resPara.setCode(CommCode.M_Y000000);
			resPara.setMessage(CommCode.M_Y000001);
		  }
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}
		
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
	//		logger.info("FocusListServlet jsonResult:" + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

	//		logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public FocusReqPara getReqPara(HttpServletRequest request) {

		FocusReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new FocusReqPara());

			reqPara = (FocusReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String page = request.getParameter("page");
			String pagesize = request.getParameter("pagesize");
	
//			logger.info("reqPara userid:" + userid);
//			logger.info("reqPara page: " + page);
//			logger.info("reqPara pagesize: " + pagesize);

	        reqPara.setPage(page);
	        reqPara.setPagesize(pagesize);
	        reqPara.setUserid(userid);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		FocusReqPara cdReqPara = (FocusReqPara) reqPara;
		BaseResponse cdResPara = (BaseResponse) resPara;

		if (StringUtils.isEmpty(cdReqPara.getPage())){
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000009);	
		} else if (StringUtils.isEmpty(cdReqPara.getPagesize())){
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000010);				
		} else if (StringUtils.isEmpty(cdReqPara.getUserid())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000002);
		} else {
			flag = true;
		}

		return  flag;
	}

}
